import React, { useRef, FC ,useState,useEffect,useImperativeHandle,forwardRef} from 'react'
import { withRouter } from 'react-router-dom'
import commom from '@/api'
import $axios from '@/utils/axios'
import { Table , Modal ,Form,Spin ,Input, Button} from 'antd';
import MyDefineSelect from '@/components/common/myDefineSelect'
import {modalLayoutSm} from '@/config/layout';
const RoleList: FC = () => {
  const tableRef: RefType = useRef()
  const [data,setdata] = useState([]);
  const [menyType,setmenyType] = useState({});
  const MenuEditRef: RefType = useRef()
  useEffect(()=>{
    getMenu();
    getMenuType();
  },[])
  const getMenu = ()=>{
    $axios.get('/dm/api/metric/define/measure-class-tree').then((res)=>{
      let data = res['data']?res['data']:[];
      data = handledata(data);
      setdata(res['data']);
    })
 }
 const handledata = (data)=>{
    data.map((e,i)=>{
      data[i]['key'] = e['measureFillCode'];
      if(e['children'].length==0){
        let obj = Object.assign(e,{});
        delete obj['children'];
        data[i] = obj;
      }else{
        let children = handledata(data[i]['children']);
        
        data[i]['children'] = children;
      }
    })

    data.sort((a,b)=>{
      return a['sno']-b['sno'];
    })
    return data;
 }
 const getMenuType = ()=>{
  $axios.post('/dm/api/sys/dict/selectDictLabel',{
    dictindex: "menuType",
    pageNum: 1,
    pageSize: 10000,
  }).then((res)=>{
    let menutypeObj ={};
    let data = res['data']['list']?res['data']['list']:[];
    data.map((e)=>{
      menutypeObj[e['optionvalue']] = e['optionlabel'];
    })
    setmenyType(menutypeObj)

  })
}

// 添加
const add = (pid) => {
  MenuEditRef.current.init('',pid);
}
 // 修改
 const edit = (id,pid) => {
  // rowEdit.current.init(id);
  MenuEditRef.current.init(id,pid);
}
// 删除
const del = (id) => {
  Modal.confirm({
    title: '确认删除？',
    
    onOk() {
      $axios.delete('/dm/api/metric/define/delmeasure-class?measureFillCode='+id).then(()=>{
        getMenu();
      })
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}
 const columns = [
  {
    title: '指标类名',
    key: 'measureTypeName',
    dataIndex: 'measureTypeName',
  },
  {
    title: '指标类标',
    key: 'measureFillFlag',
    dataIndex: 'measureFillFlag',
  },
  {
    title: '指标类类型',
    key: 'dimCode',
    dataIndex: 'dimCode',
  },
  {
    title: '操作',
    key: 'scan',
    dataIndex: 'scan',
    width: "180px",
    render:(txt,record,index)=>{
      return <>
        <a onClick={() => edit(record.measureFillCode,record.parentCode)} style={{ marginRight: '10px' }}>编辑</a>
        <a onClick={() => del(record.measureFillCode)} style={{ marginRight: '10px' }}>删除</a>
        <a onClick={() => add(record.measureFillCode)} >新增子类</a>
      </>
     
    }
  },
]
  return (
    <>
    <div style={{textAlign:'right',marginBottom:'10px'}}>
     <Button type="primary" onClick={()=>add('')}>新增大类</Button>
    </div>
    
    <Table
      bordered={true}
      pagination={false}
      columns={columns}
      dataSource={data}
      scroll={{
        y:window.innerHeight-260
      }}
    />
    <MenuEditCom ref={MenuEditRef} callback={()=>{
        getMenu();
      }}/>
    <div style={{height:'15px'}}></div>
  </>
  )
}



//类
const MenuEdit = (props, refs) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false)
  //菜单id
  const [measureFillCode,setmeasureFillCode] = useState('');
  //父id
  const [parentCode,setparentCode] = useState('');
  //父菜单name
  const [parentCodename,setparentCodename] = useState('');
  const { setFieldsValue, resetFields } = form;
  useImperativeHandle(refs, () => ({
    // 菜单id   measureFillCode_q
    // 父菜单id  parentCode_q
    init: (measureFillCode_q,parentCode_q,setparentCodename_q) => {
      setmeasureFillCode(measureFillCode_q);
      setparentCode(parentCode_q);
      setparentCodename(setparentCodename_q)
      if(measureFillCode_q){
        $axios.get('/dm/api/metric/detail/measure-class-list?measureFillCode='+measureFillCode_q).then((res)=>{
          let data = res['data'];
          setFieldsValue(data)
        })
      }else{
        resetFields();
      }
      showModal();
    }
  }))

  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      setLoading(true);
      const Obj = form.getFieldsValue()

      let fn = measureFillCode? $axios.put: $axios.post;
      let url = measureFillCode?'/dm/api/metric/define/editmeasure-class':'/dm/api/metric/define/addLdept';
      let param = measureFillCode?{
        ...Obj,
        ...{
          measureFillCode:measureFillCode,
          parentCode:parentCode
        }
      }:{
        ...Obj,
        ...{
          parentCode:parentCode
        }
      }
      fn(url,param).then((res)=>{
        handleCancel();
      }).catch(()=>{
        setLoading(false);
      })
      
    })
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    setLoading(false);
    props.callback&&props.callback();
  };

  return <Modal 
  title={measureFillCode==''?'新增指标类':'修改指标类'} 
  visible={isModalVisible} 
  onOk={handleOk} 
  onCancel={handleCancel}
  width={650}
  maskClosable={false}
  >

    <Spin spinning={loading}>
      <Form form={form} {...modalLayoutSm}>
        <Form.Item
          name="measureTypeName"
          label="指标类名"
          rules={[
            {
              required: true,
              message: '请输入指标类名'
            }
          ]}
        > 
          <Input />
        </Form.Item>
        <Form.Item
          name="measureFillFlag"
          label="指标类标"
          rules={[
            {
              required: true,
              message: '请输入指标类标'
            }
          ]}
        > 
          <Input />
        </Form.Item>
        <Form.Item
          name="dimCode"
          label="指标类类型"
          rules={[
            {
              required: true,
              message: '请输入指标类类型'
            }
          ]}
        > 
          <Input />
        </Form.Item>
      </Form>
    </Spin>
  </Modal>
}


const MenuEditCom = forwardRef(MenuEdit);





export default withRouter(RoleList)
